import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {SystemService} from "../system.service";
import {StorageService} from "../../services/storage.service";
import {FormBuilder, FormGroup} from "@angular/forms";
import {ConfirmationService, Message, TreeNode} from "primeng/primeng";

@Component({
  selector: 'app-jur-edit',
  templateUrl: './jur-edit.component.html',
  styleUrls: ['./jur-edit.component.css']
})
export class JurEditComponent implements OnInit {
  display;
  allJurs: TreeNode[];//所有权限树的数据
  ownJurs: TreeNode[];//已拥有权限树的数据
  selectedNodeData: any = [];//已选中权限的数据
  selectedNodeId: any = [];//已选中权限的ID
  selected; TreeNode;
  title;
  msgs: Message[];//提示信息
  jur: FormGroup;
  @Output() closeJurEdit =new EventEmitter();
  @Output() updateJur = new EventEmitter(); //修改角色
  @Input() currentOrg;
  @Input() state;

  constructor(
    private systemService: SystemService,
    private storageService: StorageService,
    private fb: FormBuilder,
    private confirmationService: ConfirmationService
  ) {
  }

  ngOnInit() {
    this.display = true;
    //查询所有权限树的数据
    this.queryAllJurTree('','');
    //查询已拥有权限树的数据
    this.queryOwnJurTree('','', this.currentOrg.rid);
    // console.log(this.currentOrg)
    if(this.state == 'update'){
      this.title = '编辑权限';
    }
  }

  //确定
  formSubmit(bool){
    if(this.state ==='update'){
      this.updateJurNode(bool);
    }
  }

  //修改权限
  updateJurNode(bool){
    this.selectedNodeId = [];
    this.getSelectedNodeId(this.selectedNodeData);
    if(!this.selectedNodeId.length){
      this.showWarn('请选择权限！');
    }else{
      this.systemService.updateJur(this.currentOrg.rid, this.selectedNodeId).subscribe(()=>{
        this.updateJur.emit(this.currentOrg);
        this.closeJurEdit.emit(bool);
      })
    }
  }

  closeJurEditMask(bool){
    this.closeJurEdit.emit(bool);
  }

  // 所有权限树,懒加载
  nodeExpand(event) {
    if (event.node && !event.node.children) {
      this.systemService.getAllJurTreeData(event.node.mid, event.node.dep).subscribe(data => {
        // console.log(data);
        event.node.children = data;
      })
    }
  }

  // 已拥有权限树,懒加载
  ownNodeExpand(event) {
    if (event.node && !event.node.children) {
      this.systemService.getOwnJursTreeData(event.node.mid, event.node.dep, this.currentOrg.rid).subscribe(data => {
        // console.log(data);
        event.node.children = data;
      })
    }
  }

  // 所有权限树,选中
  NodeSelect(event) {
    this.selectedNodeData = [];
    let treeData = this.allJurs;
    for(let i = 0;i < this.selected.length;i++){
      this.checkedNode(treeData, this.selected[i].id, true);
    }
    if(this.selected.length){
      this.getSelectedNodeData(treeData, this.selectedNodeData);
      this.ownJurs = this.selectedNodeData;
    }else {
      this.ownJurs = [];
    }
  }

  // 所有权限树,取消选中
  onNodeUnselect(event) {
    this.selectedNodeData = [];
    let treeData = this.allJurs;
    this.checkedNode(treeData, event.node.id, false);
    if(this.selected.length){
      this.getSelectedNodeData(treeData, this.selectedNodeData);
      this.ownJurs = this.selectedNodeData;
    }else {
      this.ownJurs = [];
    }
  }

  //复制对象
  copyObj(source) {
    var retObj = {};
    for (var key in source) {
      retObj[key] = source[key];
    }
    return retObj;
  }

  //获取选中节点的数据
  getSelectedNodeData(data, cdata) {
    for (var i = 0, len = data.length; i < len; i++) {
      if (data[i].checked) {
        cdata.push(this.copyObj(data[i]));
        cdata[cdata.length - 1].children = [];
        if (Object.prototype.toString.call(data[i].children) === '[object Array]') {
          this.getSelectedNodeData(data[i].children, cdata[cdata.length - 1].children);
        }
      }
    }
  }

  //选中或者取消节点
  checkedNode(data, id,bool) {
    for (let i = 0, len = data.length; i < len; i++) {
      if (data[i].id == id) {
        data[i].checked = bool;
        if(bool){//选中节点
          this.selectedParentNode(data[i], bool);
        }else{//取消选中
          this.noSelectedParentNode(data,bool);
          // break;
        }
      }else if (Object.prototype.toString.call(data[i].children) === '[object Array]') {//还有子节点
        this.checkedNode(data[i].children, id, bool);
      }
    }
  }

  //取消选中父节点
  noSelectedParentNode(data,bool){
    for(var j = 0;j < data.length;j++){
      if(data[j].checked && data[j].parent){
          data[j].parent.checked = !bool;
          break;
      }else{
        data[j].parent.checked = bool;
      }
    }
    if(data[0].parent && data[0].parent.parent) {//还有父节点
      this.noSelectedParentNode(data[0].parent.parent.children, bool);
    }
  }

  //选中父节点
  selectedParentNode(data,bool){
    if (data.parent) {//还有父节点
      data.parent.checked = bool;
      if(data.parent.parent){
        this.selectedParentNode(data.parent,  bool);
      }
    }
  }

  //获取选中节点的id
  getSelectedNodeId(data) {
    for (var i = 0, len = data.length; i < len; i++) {
      if (data[i].checked) {
          this.selectedNodeId.push(data[i].id);
        if (Object.prototype.toString.call(data[i].children) === '[object Array]') {
          this.getSelectedNodeId(data[i].children);
        }
      }
    }
  }

  //查询所有权限树数据
  queryAllJurTree(mid,dep){
    this.systemService.getAllJurTreeData(mid,dep).subscribe(datas => {
      // console.log(datas);
      this.allJurs = datas;
    })
  }

  //查询已拥有权限树数据
  queryOwnJurTree(mid,dep,rid){
    this.systemService.getOwnJursTreeData(mid,dep,rid).subscribe(datas => {
      console.log(datas);
      this.ownJurs = datas;
    })
  }

  showWarn(operator: string) {
    this.msgs = [];
    this.msgs.push({severity:'warn', summary:'注意', detail:operator });
  }

}
